package com.ktjiaoyu.crm.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ktjiaoyu.crm.pojo.Role;
import com.ktjiaoyu.crm.pojo.User;
import com.ktjiaoyu.crm.service.RoleService;
import com.ktjiaoyu.crm.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

@Controller
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;

    /**
     * 查询用户列表
     * @param usrName
     * @param roleId
     * @param model
     * @return
     */
    @RequestMapping(value = "/user/list")
    public String findUsers(@RequestParam(value = "pageIndex",defaultValue = "1") Integer pageIndex, String usrName, Long roleId, Model model){

        //实例化Page对象
        Page<User> page = new Page<>(pageIndex,5);

        //第一种：直接返回Page对象的分页查询
        //IPage<User> userPager = userService.getUsersByPages(page,queryWrapper);
        //第二种：返回list，再调用setRecoreds()返回page对象
        page = userService.selectUserPages(page,usrName,roleId);
        model.addAttribute("roleId",roleId);
        model.addAttribute("usrName",usrName);
        model.addAttribute("userPager",page);
        return "user/list";
    }

    /**
     * 去到新增用户页面
     * @param model
     * @return
     */
    @RequestMapping(value = "/user/add")
    public String add(Model model){
        List<Role> roleList = roleService.findAllRoles();
        model.addAttribute("roles",roleList);
        return "user/add";
    }

    /**
     * 新增用户信息
     * @param user
     * @return
     */
    @RequestMapping(value = "/user/save")
    public String save(User user){
        if(userService.addUsers(user)) return "redirect:/user/list";

        return "redirect:/user/add";
    }


}
